<template>
  <div class="my-index-container">
    <!-- Api 信息弹框 start -->
    <nut-dialog v-if="Userinfo?.businessTypeList" no-cancel-btn title="Api信息" text-align="left" closeable
      :close-on-click-overlay="true"
      :content="`appkey:\n${Userinfo?.businessTypeList[0]?.appKey}\nappSecret:\n${Userinfo?.businessTypeList[0]?.appSecret}`"
      v-model:visible="visible2">
      <template v-slot:footer>
        <div class="flex-content flex-content-light">
          <nut-button size="mini" color="linear-gradient(to right, #5232B7,#7237BC)" @click="onCopy">复制</nut-button>
        </div>
      </template>
    </nut-dialog>
    <!-- Api 信息弹框 end -->
    <div class="my-header">
      <div class="my-header-left">
        <nut-avatar size="large">
          <img :src="Userinfo.headImg" style="border-radius: 50%" />
        </nut-avatar>
        <div class="my-header-left-name">
          <div class="my-header-left-name-wxName">{{ Userinfo.nickname }}</div>
          <div class="my-header-left-name-id">{{ Userinfo.userName }}</div>
        </div>
      </div>
    </div>
    <div class="my-money-container">
      <div class="my-money-item">
        <div class="my-money-item-num">
          {{ (Userinfo.balance / 100).toFixed(2) }}
        </div>
        <div class="my-money-item-text">我的余额</div>
      </div>
      <div class="my-money-item">
        <div class="my-money-item-num">
          {{ (Userinfo.balance / 100).toFixed(2) }}
        </div>
        <div class="my-money-item-text">可用余额</div>
      </div>
      <div class="my-money-item">
        <div class="my-money-item-num">
          {{
          Userinfo.freezeBalance
          ? (Userinfo.freezeBalance / 100).toFixed(2)
          : "0.00"
          }}
        </div>
        <div class="my-money-item-text">冻结余额</div>
      </div>
    </div>
    <div class="my-logout-class">
      <div class="item" @click="handleClickAddMoney">
        <div class="text">账户充值</div>
        <IconFont name="right" color="#999" size="14px"></IconFont>
      </div>
      <div class="item" @click="handleClickAddress">
        <div class="text">我的地址</div>
        <IconFont name="right" color="#999" size="14px"></IconFont>
      </div>
      <div class="item" @click="handleClickApi">
        <div class="text">API申请</div>
        <IconFont name="right" color="#999" size="14px"></IconFont>
      </div>
      <div class="item" @click="handleClickMoney">
        <div class="text">资金日志</div>
        <IconFont name="right" color="#999" size="14px"></IconFont>
      </div>
      <div class="item" @click="Taro.navigateTo({ url: '/pages/test/index' })">
        <div class="text">测试</div>
        <IconFont name="right" color="#999" size="14px"></IconFont>
      </div>

    </div>
    <div class="logout-box">
      <nut-button type="default" block @click="logout" style="border: 0;">退出登录</nut-button>
    </div>
    <!-- 订单模块 end -->
  </div>
  <Tabbar v-if="isShow"></Tabbar>
</template>
<script setup>
import { IconFont } from "@nutui/icons-vue-taro";
import Tabbar from "../../component/Tabbar";
import { onMounted, ref, watch, onUnmounted } from "vue";
import { storeToRefs } from "pinia";
import QRCode from "qrcodejs2-fix";
import { useTabbarStore } from "../../store";
import { useUserStore } from "../../store";
import Loading from "../../component/Loading/index";
import * as orderApi from "../../api/order";
import Filter from "./filter.vue";
import Taro, { useDidShow, usePullDownRefresh } from "@tarojs/taro";
import * as loginApi from "../../api/loginApi";
const tabbarStore = useTabbarStore();
const router = Taro.useRouter();
const userStore = useUserStore();
const { selected, tabbarHeight } = storeToRefs(tabbarStore);
const { Token, Userinfo } = storeToRefs(userStore);
const list = ref([]);
const visible2 = ref(false);
const isShow = ref(true);
const filterList = ref([
  {
    id: 1,
    name: "待支付",
  },
  {
    id: 4,
    name: "待出票",
  },
  {
    id: 5,
    name: "已出票",
  },
  {
    id: 6,
    name: "已收货",
  },
  {
    id: 12,
    name: "已退票",
  },
]);
//每次进入我的页面都刷新用户信息 并且保存
useDidShow(() => {
  getListContainerHeight();

  setTimeout(() => {
    getUserInfo();
  }, 1000);
});
//订单请求参数
const info = ref({
  orderStatus: filterList.value[0].id,//订单状态
  pageSize: 5,// 数量
  currentPage: 1,// 当前页码
  userId: Userinfo.value.id,// 用户ID
});
const isSelected = ref(0);//当前选中的订单状态
const loading = ref(false); // 加载状态
const totalPage = ref(0);//总页数
const loadingFlag = ref(false);
const tipFlag = ref(false); // 加载的提示
const listContainerHeight = ref(0); // 滑动框高度
const timer = ref(null); // 定时器
const userInfo = ref({}); // 用户信息
//调用用户信息接口
const getUserInfo = async () => {
  const res = await loginApi
    .userInfo({ userId: Userinfo.value.id })
    .then((res) => res.data);
  userStore.setUserinfo(res);
  Taro.setStorageSync("userInfo", res);
};
//页面渲染模板
onMounted(() => {
  if (router.params.isSelected) {
    isSelected.value = router.params.isSelected;
    info.value.orderStatus = 4;
    info.value.currentPage = 1;
  }
  tabbarStore.setSelected(3);
  loading.value = true;
  getList(0);
});
//切换当前的tabs
const getTabs = (val) => {
  info.value.currentPage = 1;
  loading.value = true;
  info.value.orderStatus = val.id;
  getList(0);
};
// 更新列表 子组件函数
const getNewList = () => {
  info.value.currentPage = 1;
  getList(0);
};
//分页节流
const throttle = (func, delay) => {
  let lastTime = 0;
  return function () {
    const now = new Date().getTime();
    if (now - lastTime >= delay) {
      func.apply(this, arguments);
      lastTime = now;
    }
  };
};
//上拉加载
// const onScrollBottom = () => {
//   loadingFlag.value = true;
//   if (timer.value) {
//     clearTimeout(timer.value);
//   }
//   timer.value = setTimeout(() => {
//     if (info.value.currentPage < totalPage.value) {
//       info.value.currentPage++;
//       getList(1);
//     } else {
//       loadingFlag.value = false;
//       tipFlag.value = true;
//     }
//   }, 1000);
// };
//上拉加载节流
const onScrollBottom = throttle(() => {
  loadingFlag.value = true;
  tipFlag.value = false;
  if (info.value.currentPage < totalPage.value) {
    info.value.currentPage++;
    getList(1);
  } else {
    loadingFlag.value = false;
    tipFlag.value = true;
  }
}, 1000);
// 在绑定滚动事件时使用 onScrollBottom
window.addEventListener("scroll", onScrollBottom);
//获取当前的列表
const getList = async (status) => {
  const res = await orderApi.orderList(info.value);
  if (res.state == 200) {
    if (status) {
      totalPage.value = res.data.pageCount;
      list.value = [...list.value, ...res.data.list];
      loading.value = false;
      loadingFlag.value = false;
    } else {
      totalPage.value = res.data.pageCount;
      list.value = [];
      list.value = res.data.list;
      loading.value = false;
      loadingFlag.value = false;
    }
  }
};
//计算scrollview 的高度
const getListContainerHeight = () => {
  const query = Taro.createSelectorQuery()
    .select(".my-order-container")
    .boundingClientRect();
  query.selectViewport();
  query.exec(function (res) {
    if (res[0]) {
      listContainerHeight.value = res[0].height;
    }
  });
};
//进入资金明细
const handleClickMoney = () => {
  Taro.navigateTo({
    url: "/pages/fund-list/index",
  });
};
//充值页面
const handleClickAddMoney = () => {
  Taro.navigateTo({
    url: "/pages/account-recharge/index",
  });
};
const handleClickAddress = () => {
  Taro.navigateTo({
    url: "/pages/address/index",
  });
};
//申请Api
const handleClickApi = async () => {
  try {
    if (
      Userinfo.value.businessTypeList.length > 0 &&
      Userinfo.value.businessTypeList[0].appKey &&
      Userinfo.value.businessTypeList[0].appSecret
    ) {
      visible2.value = true;
      return;
    }
    const data = {
      businessType: "Film",
      userId: Userinfo.value.id,
    };
    const res = await loginApi.apiCommit(data);
    if (res.state == 200) {
      Taro.showToast({
        title: "已提交，等待审核",
        icon: "none",
        duration: 3000,
      });
    } else {
      Taro.showToast({
        title: res.message,
        icon: "none",
        duration: 3000,
      });
    }
  } catch (error) {
    Taro.showToast({
      title: "访问服务器失败,请重试~",
      icon: "none",
      duration: 3000,
    });
  }
};
//退出 登录
const logout = () => {
  userStore.loggout();
  Taro.navigateTo({
    url: "/pages/login/index",
  });
};
//复制
const onCopy = () => {
  Taro.setClipboardData({
    data: `${Userinfo?.value.businessTypeList[0].appKey}\n${Userinfo?.value.businessTypeList[0].appSecret}`, //要被复制的内容
    success: () => {
      //复制成功的回调函数
      Taro.showToast({
        //提示
        title: "复制成功",
        icon: "none",
      });
    },
  });
};
</script>
<style lang="scss">
.my-index-container {
  height: 100%;
  // padding: 20px 30px;
  display: flex;
  flex-direction: column;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow-y: auto;

  .nut-dialog__header {
    font-size: 24px;
  }

  .my-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 30px;
    position: relative;
    background-color: #fff;

    .my-header-left {
      display: flex;
      align-items: center;

      .my-header-left-name {
        display: flex;
        flex-direction: column;
        // align-items: center;
        margin-left: 25px;
        font-size: 30px;

        .my-header-left-name-wxName {
          font-weight: 700;
          color: #15181d;
        }

        .my-header-left-name-id {
          color: #858a99;
          font-size: 24px;
          margin-top: 5px;
        }
      }
    }

    .my-header-right {
      display: flex;
      align-items: center;
      background-color: #fff;
      padding: 5px 10px;
      border-radius: 10px;
      font-size: 22px;

      .money-text {
        margin-left: 8px;
      }
    }
  }

  .logout-box {
    margin-top: 20px;
    padding: 20px 60px;

  }

  .my-logout-class {
    padding: 0 20px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    background-color: #fff;

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 28px;
      color: #858a99;
      padding: 20px;
    }

  }

  .my-header::before {
    content: "";
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: 1rpx;
    /* 控制线的高度 */
    background: linear-gradient(to right, #5232b7, #7237bc);
    content: "";
    display: block;
    margin: 0 auto;
    opacity: 0.2;
  }

  .my-money-container {
    display: flex;
    align-items: center;
    // margin-top: 50px;
    padding: 20px 30px;
    background-color: #fff;

    .my-money-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      flex: 1;

      .my-money-item-num {
        font-weight: 700;
        color: #15181d;
        font-size: 28px;
      }

      .my-money-item-text {
        color: #858a99;
        font-size: 28px;
      }
    }
  }

  .my-order-container {
    padding: 0 10px;
    border-radius: 15px;
    flex: 1;

    .flex-container1 {
      padding: 20px;

      .flex-item:last-child {
        margin-bottom: 100px;
      }

      .flex-item {
        background-color: #fff;
        margin-top: 15px;
        border-radius: 15px;
      }

      .flex-item:nth-child(n + 2) {
        margin-top: 15px;
      }
    }
  }

  .my-order-container-row1 {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .my-order-container-row1-left {
      color: #15181d;
      font-weight: 700;
      font-size: 28px;
    }

    .my-order-container-row1-right {
      display: flex;
      align-items: center;
      color: #858a99;
      font-size: 28px;
    }
  }

  .my-order-container-row2 {
    display: flex;
    align-items: center;
    margin-top: 50px;

    .my-order-container-row2-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;

      .my-order-container-row2-item-title {
        font-size: 28px;
        margin-top: 8px;
        color: #858a99;
      }
    }
  }
}

.my-setting-container {
  margin-top: 30px;
}
</style>
